<template>
	<div class="layout">
		<Layout :style="{ minHeight: '100vh' }">
			<Sider
				ref="side1"
				hide-trigger
				collapsible
				:collapsed-width="0"
				v-model="isCollapsed"
				:width="310"
				:style="{
					'background-color': '#fff',
					'border-right': '1px solid #ddd',
				}"
			>
				<MainList :mainNftList="this.sortAssets"></MainList>
			</Sider>
			<Layout>
				<Header :style="{ padding: 0 }" class="layout-header-bar">
					<Icon
						@click.native="collapsedSider"
						:class="rotateIcon"
						:style="{ margin: '0 20px' }"
						type="ios-arrow-dropleft"
						size="24"
					></Icon>
				</Header>
				<Content
					:style="{
						margin: '0px',
						background: '#fff',
						minHeight: '260px',
						overflow: 'hidden',
					}"
				>
					<HomeContent :homeContentNftList="this.assets" />
				</Content>
			</Layout>
		</Layout>
	</div>
</template>

<script>
// import TopList from './TopList.vue';
import MainList from './MainList.vue';
import HomeContent from './HomeContent.vue';
import Web3 from 'web3';
import { addressLogin, userinfo, getUserInfoByAddress } from '@/api';
import { NETWORKID, CONTRACTBUILD } from '@/config';
// import { BASEURL } from "@/config";

export default {
	components: {
		// TopList,
		MainList,
		HomeContent,
	},
	data() {
		return {
			isCollapsed: false,
			NETWORK_ID: NETWORKID,
			web3: Web3,
			// VRPressToken: '',
			myAddress: '',
			assets: [],
			sortAssets: [],
		};
	},
	computed: {
		rotateIcon() {
			return ['menu-icon', this.isCollapsed ? 'rotate-icon' : ''];
		},
		menuitemClasses() {
			return ['menu-item', this.isCollapsed ? 'collapsed-menu' : ''];
		},
	},
	methods: {
		collapsedSider() {
			this.$refs.side1.toggleCollapse();
		},
		compare(propertyName) {
			return function(object1, object2) {
				var value1 = parseFloat(object1[propertyName]);
				var value2 = parseFloat(object2[propertyName]);
				if (value2 < value1) {
					return -1;
				} else if (value2 > value1) {
					return 1;
				} else {
					return 0;
				}
			};
		},

		async getWeb3() {
			var web3;
			if (window.ethereum) {
				// Modern dapp browsers
				web3 = new Web3(window.ethereum);
				try {
					// metamaskが開いて権限許可を尋ねる
					await window.ethereum.enable();
				} catch (error) {
					// 拒否した場合に入ってくる
					console.log('denied');
				}
			} else if (window.web3) {
				// Legacy dapp browsers...
				web3 = new Web3(window.web3.currentProvider);
			} else {
				// this.selectedModal = this.MODALS.METAMASK
				// this.openModal({
				// 	title: "confirm",
				// 	isOnlyConfirm: true
				// })
			}

			web3 = new Web3(window.web3.currentProvider);
			return web3;
		},
		getDeployData() {
			return require(`../../../zos.dev-${this.NETWORK_ID}.json`);
		},
		async loginAction() {
			if (this.myAddress.length !== 42) {
				console.log('login error!');
				alert('连接钱包失败，请连接钱包！');
				return;
			}
			let res = await addressLogin({
				address: this.myAddress,
				lang: 'zh_CN',
				// role: this.isUser ? "User" : "Institution"
			});

			if (res.status == 200) {
				// let msg = res.data.msg;
				// const h = this.$createElement;
				// this.$message({
				//   message: h("p", null, [
				//     h("span", null, msg),
				//     h(
				//       "i",
				//       {
				//         style: "color: teal"
				//       },
				//       ""
				//     )
				//   ])
				// });

				if (res.data.code == 0) {
					localStorage.setItem(
						'Authorization',
						res.data.data.token_type +
							' ' +
							res.data.data.access_token
					);
					// console.log("login ok");

					this.getUserInfo();
					//   setTimeout(() => {
					//     if(this.pathname != '' && this.pathname != undefined){
					//     this.$router.push(this.pathname+this.search.replace(/@/g,'&'));//把url中的@替换回&方便传参

					//     }else{
					//     this.$router.push("/");

					//     }

					//   }, 1500);
				}
			}
		},
		async getUserInfo() {
			let res = await userinfo({ lang: 'zh_CN' });
			//   this.$store.commit("user/login", res.data.data);
			localStorage.setItem('UserInfo', JSON.stringify(res.data.data));
		},
	},
	async mounted() {
		this.web3 = await this.getWeb3();
		await this.web3.eth.getAccounts((error, accounts) => {
			if (error) {
				console.log('error');
				return;
			}
			this.myAddress = accounts[0];
			console.log('my address is' + this.myAddress);
			this.$emit('transferUser', this.myAddress);
			//自动登录逻辑 todo
			this.loginAction();
			localStorage.setItem('address', this.myAddress);
		});

		const contractData = require('../../../' +
			CONTRACTBUILD +
			'/contracts/AssetToken.json');
		const deployData = this.getDeployData();
		// const tokenProxyAdresses = deployData.proxies["marketplace/AssetToken"]
		const VRPressTokenAddress = deployData.contracts.AssetToken.address;

		const VRPressToken = await new this.web3.eth.Contract(
			contractData.abi,
			// tokenProxyAdresses[tokenProxyAdresses.length - 1].address
			VRPressTokenAddress
		);

		const totalSupply = await VRPressToken.methods.totalSupply().call();

		//todo 通过total进行分页处理

		// console.log("total is :" + totalSupply);
		for (let i = 0; i < totalSupply; i++) {
			const token = await VRPressToken.methods.getToken(i).call();
			var userAddress = token['6'];
			let res = await getUserInfoByAddress({
				address: userAddress,
				lang: 'zh_CN',
			});
			var userAvatar = '';
			if (res.status == 200) {
				if (res.data.code == 0) {
					userAvatar = res.data.data.avatar;
				}
			}
			//   console.log(token);
			const asset = {
				id: token['0'],
				name: token['1'],
				uri: token['3'],
				price: +this.web3.utils.fromWei(token[4].toString(), 'ether'),
				forSale: token['5'],
				owner: token['6'],
				avatar: userAvatar,
			};

			this.sortAssets.push(asset);
			this.assets.push(asset);
		}
		//nft列表

		this.assets.reverse();
		console.log(this.assets);
		await this.sortAssets.sort(this.compare('price'));
		this.sortAssets = this.sortAssets.slice(0,12);//排行榜显示前12个
	},
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.layout {
	border: 1px solid #d7dde4;
	background: #f5f7f9;
	position: relative;
	border-radius: 4px;
	overflow: hidden;
	height: 90vh;
}
.layout-header-bar {
	background: #fff;
	box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}
.layout-logo-left {
	width: 90%;
	height: 30px;
	background: #5b6270;
	border-radius: 3px;
	margin: 15px auto;
}
.menu-icon {
	transition: all 0.3s;
}
.rotate-icon {
	transform: rotate(-180deg);
}
.menu-item span {
	display: inline-block;
	overflow: hidden;
	width: 69px;
	text-overflow: ellipsis;
	white-space: nowrap;
	vertical-align: bottom;
	transition: width 0.2s ease 0.2s;
}
.menu-item i {
	transform: translateX(0px);
	transition: font-size 0.2s ease, transform 0.2s ease;
	vertical-align: middle;
	font-size: 16px;
}
.collapsed-menu span {
	width: 0px;
	transition: width 0.2s ease;
}
.collapsed-menu i {
	transform: translateX(5px);
	transition: font-size 0.2s ease 0.2s, transform 0.2s ease 0.2s;
	vertical-align: middle;
	font-size: 22px;
}
</style>
